const { Sheet, FileFolder, User } = require('../model')
const pako = require("pako");
exports.createSheet = async (req, res, next) => {
    try {
        let sheetData = [
            //status为1的sheet页，重点是需要提供初始化的数据celldata
            {
                "name": "Sheet1",
                "index": "sheet_01",
                "order": 0,
                "status": 1,
            },
            //其他status为0的sheet页，无需提供celldata，只需要配置项即可
            {
                "name": "Sheet2",
                "index": "sheet_02",
                "order": 1,
                "status": 0
            },
            {
                "name": "Sheet3",
                "index": "sheet_03",
                "order": 2,
                "status": 0
            }
        ]
        let newData = {
            title: '未命名表格',
            content: JSON.stringify(sheetData),
            author: req.body._id,
            permissionsId: [req.body._id]
        }
        const sheet = new Sheet(newData);
        await sheet.save();
        const fileFolder = await FileFolder.findOne({ author: req.body._id })
        if (fileFolder.allSheet.indexOf(sheet._id) == -1) {
            fileFolder.allSheet.push(sheet._id)
            await fileFolder.save()
        }
        res.status(200).json(
            {
                code: 200,
                data: sheet,
                msg: '创建表格成功'
            }
        )
    } catch (err) {
        next(err);
    }
};

exports.getSheet = async (req, res, next) => {
    try {
        const sheet = await Sheet.findById(req.query.id);
        if (req.query.type == 'sheet') {
            return res.status(200).json(sheet.content);
        }
        if (!sheet) {
            return res.status(404).json({
                code: 404,
                data: '表格不存在'
            });
        }
        if (sheet.permissionsId.indexOf(req.query.userId) == -1) {
            return res.status(200).json({
                code: 400,
                data: '无权获取表格'
            });
        }
        sheet.permissionsId = await Promise.all(sheet.permissionsId.map(async (permission) => {
            const user = await User.findById(permission);
            return { _id: user._id, username: user.username, email: user.email, avatar: user.avatar };
        }))
        res.status(200).json(
            {
                code: 200,
                data: sheet,
                msg: '获取表格成功'
            }
        )
    } catch (err) {
        next(err);
    }
};

exports.getUpdateSheet = async (req, res, next) => {
    try {
        let updatedSheet
        const { id, content, author } = req.body;
        const fileFolder = await FileFolder.findOne({ author: author })
        if (fileFolder.recentSheet.indexOf(id) == -1) {
            fileFolder.recentSheet.push(id)
            await fileFolder.save()
        }
        if (req.body.title) {
            await Sheet.updateOne({ _id: id }, { title: req.body.title });
        } else {
            updatedSheet = await Sheet.findOneAndUpdate(
                { _id: id },
                { $set: { content: new TextDecoder().decode(pako.inflate(content)), updatedAt: new Date() } },
                { new: true }
            );
            if (!updatedSheet) {
                // 如果没有找到文档，可以返回一个错误  
                return res.status(404).json({ code: 404, msg: '表格不存在' });
            }
        }

        // 响应更新成功  
        res.status(200).json({ code: 200, msg: '修改成功', updatedSheet });
    } catch (err) {
        console.log(err);

        next(err);
    }
};

exports.delSheetUser = async (req, res, next) => {
    try {
        const sheet = await Sheet.findById(req.body.id);
        sheet.permissionsId = sheet.permissionsId.filter((permission) => {
            return permission != req.body.userId
        })
        const filefolder = await FileFolder.findOne({ author: req.body.userId })
        filefolder.allSheet = filefolder.allSheet.filter((sheetId) => {
            return sheetId != sheet._id
        })
        filefolder.sharedSheet = filefolder.sharedSheet.filter((sheetId) => {
            return sheetId != sheet._id
        })
        await filefolder.save()
        await sheet.save()
        res.status(200).json(
            {
                code: 200,
                data: sheet,
                msg: '删除成功'
            }
        )
    } catch (err) {
        next(err);
    }
}
exports.addSheetUser = async (req, res, next) => {
    try {
        const sheet = await Sheet.findById(req.body.id);
        sheet.permissionsId.push(req.body.userId)
        const filefolder = await FileFolder.findOne({ author: req.body.userId })
        filefolder.allSheet.push(sheet._id)
        filefolder.sharedSheet.push(sheet._id)
        await filefolder.save()
        await sheet.save()
        res.status(200).json(
            {
                code: 200,
                data: sheet,
                msg: '添加成功'
            }
        )
    } catch (err) {
        next(err);
    }
}
exports.addFavorites = async (req, res, next) => {
    try {
        const { id, userId } = req.body
        const sheet = await Sheet.findById(id);
        const fileFolder = await FileFolder.findOne({ author: userId })
        fileFolder.starredSheet.push(id)
        sheet.favoriteAuthor.push(userId)
        await fileFolder.save()
        await sheet.save()
        res.status(200).json(
            {
                code: 200,
                data: sheet,
                msg: '收藏成功'
            }
        )
    } catch (err) {
        console.log(err);

        next(err);
    }
}

exports.delFavorites = async (req, res, next) => {
    try {
        const { id, userId } = req.body
        const sheet = await Sheet.findById(id);
        sheet.favoritesId = sheet.favoritesId.filter((favoriteId) => {
            return favoriteId != userId
        })
        await sheet.save()
        res.status(200).json(
            {
                code: 200,
                data: sheet,
                msg: '取消收藏成功'
            }
        )
    } catch (err) {
        next(err);
    }
}